package com.example.gkcircle.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.avos.avoscloud.AVACL;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.example.gkcircle.App;
import com.example.gkcircle.BaseActivity;
import com.example.gkcircle.R;
import com.example.gkcircle.library.object.URL;
import com.example.gkcircle.utils.ACache;
import com.example.gkcircle.utils.ActivityUtil;
import com.example.gkcircle.utils.CommonUtil;
import com.example.gkcircle.utils.FileUtil;
import com.example.gkcircle.utils.MyAlertView;
import com.example.gkcircle.utils.MySVProgressHUD;
import com.example.gkcircle.utils.PicUtil;
import com.example.gkcircle.utils.StringUtil;
import com.example.gkcircle.utils.TextWatcherListener;
import com.example.gkcircle.utils.ThreadPoolUtils;
import com.example.gkcircle.utils.ToastFactory;
import com.kyleduo.switchbutton.SwitchButton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.next.tagview.TagCloudView;

/**
 * 约吗发布
 * Created by Jehu on 16/3/29.
 */
public class ComposeLoveActivity extends BaseActivity implements View.OnClickListener{

    private TagCloudView mTagView;
    private TagCloudView mSelectedTags;
    private LinearLayout mTagViewLayout;
    private LinearLayout mSwitchLayout;
    private SwitchButton mSwitchButton;
    //ActionBar
    private ImageButton mBackBtn;
    private ImageButton mComposeBtn;
    private TextView mRightText;
    private RelativeLayout mTabbarBg;
    //剩余输入量
    private TextView mLeftTextNum;
    private EditText mContentEdit;
    private ImageView mAddPictureBtn;
    private ImageButton mDeletePicBtn;

    private final int MOVIE_CODE=0;
    private final int LOVE_CODE=1;
    private final int WISH_CODE=2;

    //调用相机和系统相册请求码
    private final int CAMERA_CODE=0;
    private final int GET_IMAGE_CODE=1;
    //约吗发布标识
    private  int mFlag;
    //压缩图片完成启程发布线程
    private Thread mCompressThread;
    //是否压缩完成
    private Boolean isFinishCompressed=false;
    //缩略图
    private Bitmap photo;
    //图片路径
    private String path;
    //压缩图片的路径
    private String tempPath;
    private final int maxTextCount=60;
    //标签组
    private List<String> tagList;
    //已选择标签
    private List<String> selectedTagList;
    //已选择标签的位置
    private List<Integer> positionList;
    //随机颜色值
    private List<Integer> randomColorList;
    private final int [] tagBgColors={R.drawable.tag_action_bg,R.drawable.tag_advanture_bg,R.drawable.tag_comedy_bg,R.drawable.tag_default_bg,R.drawable.tag_love_bg};
    @Override
    protected void initView() {
        setContentView(R.layout.love_compose_activity);
        mTagView=(TagCloudView)this.findViewById(R.id.love_compose_tagcloud);
        mSelectedTags=(TagCloudView)this.findViewById(R.id.love_compose_tags);
        mTabbarBg=(RelativeLayout)this.findViewById(R.id.tabbar_bg);
        mBackBtn=(ImageButton)this.findViewById(R.id.tabbar_left_btn);
        mComposeBtn=(ImageButton)this.findViewById(R.id.tabbar_right_btn);
        mRightText=(TextView)this.findViewById(R.id.tabbar_right_text);
        mLeftTextNum=(TextView)this.findViewById(R.id.love_compose_left);
        mContentEdit=(EditText)this.findViewById(R.id.love_compose_content);
        mAddPictureBtn=(ImageView)this.findViewById(R.id.love_compose_add_picture);
        mDeletePicBtn=(ImageButton)this.findViewById(R.id.love_compose_delete_picture_btn);
        mTagViewLayout=(LinearLayout)this.findViewById(R.id.love_compose_tagview_layout);
        mSwitchLayout=(LinearLayout)this.findViewById(R.id.love_compose_switch_layout);
        mSwitchButton=(SwitchButton)this.findViewById(R.id.love_compose_switch);
    }

    @Override
    protected void initListener() {
        mBackBtn.setOnClickListener(this);
        mComposeBtn.setOnClickListener(this);
        mAddPictureBtn.setOnClickListener(this);
        mDeletePicBtn.setOnClickListener(this);
        mRightText.setOnClickListener(this);
        mContentEdit.addTextChangedListener(new TextWatcherListener(mLeftTextNum, mContentEdit, maxTextCount));
        mLeftTextNum.setText(maxTextCount + "");

        mSwitchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    mSwitchButton.setThumbColorRes(R.color.love);
                    mSwitchButton.setTextColor(getResources().getColor(R.color.love));
                }else{
                    mSwitchButton.setThumbColorRes(R.color.date_grey);
                    mSwitchButton.setTextColor(getResources().getColor(R.color.date_grey));
                }
            }
        });
    }


    @Override
    protected void setData() {
        //默认设置
        mBackBtn.setBackground(getResources().getDrawable(R.mipmap.back_white));
        mComposeBtn.setVisibility(View.GONE);
        mRightText.setTextColor(getResources().getColor(R.color.white));
        //获取标识
        Bundle bundle=this.getIntent().getExtras();
        mFlag=bundle.getInt("flag");

        switch (mFlag){
            //约电影
            case MOVIE_CODE:
                setTags(null);
                mSwitchLayout.setVisibility(View.GONE);
                mSelectedTags.setVisibility(View.VISIBLE);
                mTagViewLayout.setVisibility(View.VISIBLE);
                mAddPictureBtn.setVisibility(View.VISIBLE);
                mContentEdit.setHint(getResources().getString(R.string.movie_hint));
                mLeftTextNum.setTextColor(getResources().getColor(R.color.main));
                mTabbarBg.setBackgroundColor(getResources().getColor(R.color.main));
                mRightText.setText("约电影");
                //获取标签
                getMovieTags(new OnGetMovieTagListener() {
                    @Override
                    public void complete(JSONObject response) {
                        //不为空缓存JSON
                        if (response != null)ACache.get(ComposeLoveActivity.this).put("movieTagJSON", response);
                        setTags(response);
                    }
                });
                break;
            case LOVE_CODE:
                mSelectedTags.setVisibility(View.GONE);
                mTagViewLayout.setVisibility(View.GONE);
                mAddPictureBtn.setVisibility(View.GONE);
                mSwitchLayout.setVisibility(View.VISIBLE);
                mLeftTextNum.setTextColor(getResources().getColor(R.color.love));
                mTabbarBg.setBackgroundColor(getResources().getColor(R.color.love));
                mRightText.setText("表白");
                AVUser user=AVUser.getCurrentUser();
                if(user==null)break;
                if(user.getBoolean("sex")){
                    mContentEdit.setHint(getResources().getString(R.string.love_boy_hint));
                }else{
                    mContentEdit.setHint(getResources().getString(R.string.love_girl_hint));
                }
                break;
            case WISH_CODE:
                mSwitchLayout.setVisibility(View.GONE);
                mSelectedTags.setVisibility(View.GONE);
                mTagViewLayout.setVisibility(View.GONE);
                mAddPictureBtn.setVisibility(View.VISIBLE);
                mContentEdit.setHint(getResources().getString(R.string.wish_hint));
                mLeftTextNum.setTextColor(getResources().getColor(R.color.wish));
                mTabbarBg.setBackgroundColor(getResources().getColor(R.color.wish));
                mRightText.setText("许心愿");
                break;
            default:
                return;
        }

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.tabbar_left_btn:
                finish();
                break;
            case R.id.tabbar_right_btn:
                break;
            //发布
            case R.id.tabbar_right_text:
                AVUser user=AVUser.getCurrentUser();
                if(user==null){
                    ToastFactory.getToast(this,getResources().getString(R.string.not_login)).show();
                    ActivityUtil.startActivity(this, LoginActivity.class);
                    return;
                }
                final String content=mContentEdit.getText().toString().trim();
                switch (mFlag){
                    //约电影发布
                    case MOVIE_CODE:
                        if(content.isEmpty()){
                            MySVProgressHUD.getInstance(ComposeLoveActivity.this).showInfoWithStatus(getResources().getString(R.string.no_movie_content_tips));
                            return;
                        }
                        if(null!=selectedTagList && selectedTagList.isEmpty()){
                            MySVProgressHUD.getInstance(ComposeLoveActivity.this).showInfoWithStatus("至少要选择一个标签哦");
                            return;
                        }
                        if(null==path || path.isEmpty()){
                            MySVProgressHUD.getInstance(ComposeLoveActivity.this).showInfoWithStatus(getResources().getString(R.string.movie_have_a_picture));
                            return;
                        }
                        break;
                    //表白墙发布
                    case LOVE_CODE:
                        if(content.isEmpty()){
                            MySVProgressHUD.getInstance(ComposeLoveActivity.this).showInfoWithStatus(getResources().getString(R.string.no_love_content_tips));
                            return;
                        }
                        break;
                    //心愿墙发布
                    case WISH_CODE:
                        if(content.isEmpty()){
                            MySVProgressHUD.getInstance(ComposeLoveActivity.this).showInfoWithStatus(getResources().getString(R.string.no_wish_content_tips));
                            return;
                        }
                        if(null==path || path.isEmpty()){
                            MySVProgressHUD.getInstance(ComposeLoveActivity.this).showInfoWithStatus(getResources().getString(R.string.wish_have_a_picture));
                            return;
                        }
                        break;
                    default:
                        break;
                }
                CommonUtil.hideSoftInputView(this);
                MySVProgressHUD.getInstance(ComposeLoveActivity.this).showWithStatus(getResources().getString(R.string.home_lost_composing));

                if(path!=null && !path.isEmpty()){
                    //已压缩完发可发布
                    if(isFinishCompressed){
                        compose(content);
                        return;
                    }
                    //等待压缩图片完成的线程
                    mCompressThread=new Thread(new Runnable() {
                        @Override
                        public void run() {
                            compose(content);
                        }
                    });
                }else{
                    //无图片直接发布
                    compose(content);
                }
                break;
            case R.id.love_compose_add_picture:
                if(path==null){
                    CommonUtil.hideSoftInputView(this);
                    new AlertView("上传相片", null, "取消", null, new String[]{"拍照", "从手机相册选择"}, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            switch (position){
                                case CAMERA_CODE:
                                    ThreadPoolUtils.execute(new Runnable() {
                                        @Override
                                        public void run() {
                                            PicUtil.openCamera(ComposeLoveActivity.this,CAMERA_CODE);
                                        }
                                    });
                                    break;
                                case GET_IMAGE_CODE:
                                    //调用相册
                                    ThreadPoolUtils.execute(new Runnable() {
                                        @Override
                                        public void run() {
                                            PicUtil.openAlbum(ComposeLoveActivity.this, GET_IMAGE_CODE);
                                        }
                                    });
                                    break;
                            }
                        }
                    }).show();

                }else{
                    Intent intent=new Intent(this,PhotoViewAcitivty.class);
                    Bundle bundle=new Bundle();
                    bundle.putString("imagePath",path);
                    intent.putExtras(bundle);
                    this.overridePendingTransition(0, R.anim.zoom_in);
                    this.startActivity(intent);
                }
                break;
            case R.id.love_compose_delete_picture_btn:
                if(null!=path){
                    CommonUtil.hideSoftInputView(this);
                    MyAlertView.alertView=null;
                    MyAlertView.showAlertViewWithOKAndCancel(this, "是否移除图片?", new MyAlertView.IShowAlertViewWithOkAndCancelListener() {
                        @Override
                        public void onclickOk() {
                            mDeletePicBtn.setVisibility(View.GONE);
                            mAddPictureBtn.setBackground(ComposeLoveActivity.this.getResources().getDrawable(R.mipmap.home_lost_add_picture_btn));
                            path=null;
                            tempPath=null;
                            isFinishCompressed=false;
                            //回收图片
                            if(!photo.isRecycled()){
                                photo.recycle();
                            }
                            //删除相片
                            FileUtil.deleteFile(FileUtil.MYPATHIMAGE + "tempImage.jpg");
                        }
                    });
                }
                break;
        }
    }



    private void compose(String content){
        AVUser user= AVUser.getCurrentUser();
        AVObject avObject = null;
        switch (mFlag){
            //发表约电影
            case MOVIE_CODE:
                avObject=new AVObject("Movie");
                avObject.put("user",user);
                avObject.put("content",content);
                avObject.put("tags", selectedTagList);
                avObject.put("sex",user.getBoolean("sex"));
                //设置评论数
                AVObject commentCount=new AVObject("Likes");
                commentCount.put("likeCount",0);
                commentCount.saveInBackground();
                avObject.put("commentCount", commentCount);
                break;
            //发表表白
            case LOVE_CODE:
                avObject=new AVObject("Love");
                avObject.put("user",user);
                avObject.put("content",content);
                avObject.put("anonymous",mSwitchButton.isChecked());
                break;
            //发表心愿
            case WISH_CODE:
                avObject=new AVObject("Wish");
                avObject.put("user", user);
                avObject.put("content",content);
                break;
        }
        //添加图片（无则不会执行）
        if(path!=null && tempPath!=null){
            try {
                AVFile file=AVFile.withAbsoluteLocalPath(StringUtil.filterPhotoName(path),tempPath);
                //保存图片宽高元信息
                BitmapFactory.Options options= PicUtil.getImageWHFromPath(tempPath);
                file.addMetaData("width",options.outWidth);
                file.addMetaData("height", options.outHeight);
                avObject.put("photo", file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                MySVProgressHUD.getInstance(ComposeLoveActivity.this).showErrorWithStatus(getResources().getString(R.string.home_lost_compose_error));
                return;
            }
        }
        //设置like表
        AVObject likes=new AVObject("Likes");
        likes.put("likeCount",0);
        likes.saveInBackground();
        avObject.put("like", likes);

        //添加权限
        AVACL  acl = new AVACL();
        //所有人可读
        acl.setPublicReadAccess(true);
        //发布者可写
        acl.setWriteAccess(user,true);

        avObject.setACL(acl);

        //最后保存
        avObject.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    if (tempPath != null) {
                        FileUtil.deleteFile(tempPath);
                    }
                    ComposeLoveActivity.this.setResult(RESULT_OK);
                    finish();
                } else {
                    Log.i("Compose", "done: " + e);
                    MySVProgressHUD.getInstance(ComposeLoveActivity.this).showErrorWithStatus(getResources().getString(R.string.home_lost_compose_error));
                }
                MySVProgressHUD.getInstance(ComposeLoveActivity.this).dismiss();
            }
        });
    }

    //设置电影标签
    private void setTags(JSONObject response) {
        if (response==null){
            response = ACache.get(ComposeLoveActivity.this).getAsJSONObject("movieTagJSON");
            if (response == null) {
                return;
            }
        }
        //初始化
        if (null == tagList) {
            tagList = new ArrayList<String>();
        }
        if (null == selectedTagList) {
            selectedTagList = new ArrayList<String>();
        }
        if (null == randomColorList) {
            randomColorList = new ArrayList<Integer>();
        }
        if (null == positionList) {
            positionList = new ArrayList<Integer>();
        }
        tagList.clear();
        selectedTagList.clear();
        randomColorList.clear();
        positionList.clear();
        try {
            //解析标签数组
            JSONArray array = response.getJSONArray("subjects");
            for (int i = 0; i < array.length(); i++) {
                JSONObject tag = array.getJSONObject(i);
                tagList.add(tag.get("title").toString());
            }
            //设置标签组
            mTagView.setTags(tagList);
            //设置标签背景随机色
            for (int i = 0; i < mTagView.getChildCount(); i++) {
                int random = (int) (Math.random() * 5);
                mTagView.getChildAt(i).setBackgroundResource(tagBgColors[random]);
                //记录随机的颜色
                randomColorList.add(random);
            }
            //选择标签事件
            mTagView.setOnTagClickListener(new TagCloudView.OnTagClickListener() {
                @Override
                public void onTagClick(int position) {
                    //position不能大于三（标签最多为3）
                    if (position != -1 && positionList.size() < 3) {
                        //查找已选择的标签 存在则不再添加
                        for (int i : positionList) {
                            if (i == position) return;
                        }
                        //添加标签
                        selectedTagList.add(tagList.get(position));
                        //记录添加标签的下标
                        positionList.add(position);
                        //添加选择的标签到View里
                        mSelectedTags.setTags(selectedTagList);
                        //设置随机背景色(因为会覆盖前面的颜色，所以要遍历出来重新设置)
                        for (int i = 0; i < positionList.size(); i++) {
                            mSelectedTags.getChildAt(i).setBackgroundResource(tagBgColors[randomColorList.get(positionList.get(i))]);
                        }

                    } else {
                        MySVProgressHUD.getInstance(ComposeLoveActivity.this).showInfoWithStatus("最多只能添加三个标签");
                    }
                }
            });

            //已选择标签事件
            mSelectedTags.setOnTagClickListener(new TagCloudView.OnTagClickListener() {
                @Override
                public void onTagClick(int position) {
                    if (position != -1) {
                        selectedTagList.remove(position);
                        positionList.remove(position);
                        mSelectedTags.setTags(selectedTagList);
                        //设置随机背景色(因为会覆盖前面的颜色，所以要遍历出来重新设置)
                        for (int i = 0; i < positionList.size(); i++) {
                            mSelectedTags.getChildAt(i).setBackgroundResource(tagBgColors[randomColorList.get(positionList.get(i))]);
                        }
                    }
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //获取电影标签回调接口
    public OnGetMovieTagListener onGetMovieTagListener;
    private interface OnGetMovieTagListener{
        void complete(JSONObject response);
    }

    //获取电影标签
    private void getMovieTags(final OnGetMovieTagListener onGetMovieTagListener){
        this.onGetMovieTagListener=onGetMovieTagListener;
        JsonObjectRequest request=new JsonObjectRequest(URL.doubanMovieAPI, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                onGetMovieTagListener.complete(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onGetMovieTagListener.complete(null);
            }
        });
        App.getmHttpQueue().add(request);
    }

    private static OnCompressListener onCompressListener;
    private interface OnCompressListener{
        void complete();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!=RESULT_OK){
            FileUtil.deleteFile(FileUtil.MYPATHIMAGE+"tempImage.jpg");
            return;
        }
        switch (requestCode){
            case CAMERA_CODE:
                path=FileUtil.MYPATHIMAGE+"tempImage.jpg";
                break;
            case GET_IMAGE_CODE:
                photo=null;
                Uri photoUri = data.getData();        //获得图片的uri
                //ContentResolver resolver = getContentResolver();
                //photo = MediaStore.Images.Media.getBitmap(resolver, photoUri);
                //获取选取图片路径
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor cursor = managedQuery(photoUri, proj, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                //根据索引值获取图片路径
                path = cursor.getString(column_index);
                break;
        }
        int size=PicUtil.px2dip(this, 144);
        //获取缩略图
        photo=PicUtil.getImageThumbnail(path, size, size);
        //设置图片
        mAddPictureBtn.setBackground(PicUtil.bitmapToDrawble(photo,this));
        mDeletePicBtn.setVisibility(View.VISIBLE);

        //压缩图片回调方法
        ComposeLoveActivity.onCompressListener=new OnCompressListener(){

            @Override
            public void complete() {
                //如果线程不为null 则启动发布线程
                if(mCompressThread!=null){
                    mCompressThread.start();
                }
            }
        };
        //开启压缩图片线程
        //压缩图片到100KB以下
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                //设置被压缩图片输出的路径
                tempPath = FileUtil.MYPATHIMAGE + StringUtil.filterPhotoName(path);
                //执行压缩
                PicUtil.compressedImageAndOut(path, tempPath);
                isFinishCompressed = true;
                //压缩完回调
                ComposeLoveActivity.onCompressListener.complete();
            }
        });

    }
}
